package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Category;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchProductServlet extends HttpServlet {
    private CatalogService catalogService;
    private static final String MAIN_FORM = "/WEB-INF/jsp/catalog/main.jsp";
    private static final String CATEGORY_FORM = "/WEB-INF/jsp/catalog/category.jsp";
    private static final String PRODUCT_FORM = "/WEB-INF/jsp/catalog/product.jsp";
    private static final String ITEM_FORM = "/WEB-INF/jsp/catalog/item.jsp";


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String keyword = req.getParameter("keyword");
        String ways=req.getParameter("ways");
        if(keyword!=null&&keyword!="") {
            if(ways.equals("category")) {
                catalogService = new CatalogService();
                List<Product> productList = catalogService.searchProductList(keyword);
                HttpSession session = req.getSession();
                session.setAttribute("productList", productList);
                req.getRequestDispatcher(CATEGORY_FORM).forward(req, resp);
            } else {
                catalogService = new CatalogService();
                List<Item> itemList = catalogService.searchItemListByProductName(keyword);
                HttpSession session = req.getSession();
                session.setAttribute("itemList",itemList);
                req.getRequestDispatcher(PRODUCT_FORM).forward(req,resp);
                System.out.println(itemList);
            }
        }else{
            req.getRequestDispatcher(MAIN_FORM).forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
